package logic

import (
	"context"
	"fmt"
	"mooc_srv/model/mysql"
	"mooc_srv/pkg"
	"strconv"

	"mooc_srv/internal/svc"
	"mooc_srv/mooc"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderAddLogic) OrderAdd(in *mooc.OrderAddRequest) (*mooc.OrderAddResponse, error) {
	// todo: add your logic here and delete this line
	g := mysql.Goods{}
	err := g.WhereGoods(int(in.GoodsId))
	if err != nil {
		return nil, fmt.Errorf("商品信息获取失败")
	}
	if g.ID == 0 {
		return nil, fmt.Errorf("商品不存在")
	}
	if g.GoodsSum < int(in.OrderSum) {
		return nil, fmt.Errorf("库存不足")
	}
	o := mysql.Orders{
		GoodsTitle:    g.GoodsTitle,
		UserId:        int(in.Userid),
		GoodsId:       int(in.GoodsId),
		OrdersSn:      in.OrderSn,
		OrderSun:      int(in.OrderSum),
		OrdersState:   1,
		OrdersAmount:  float64(in.OrderAmount),
		OrdersPayment: int(in.OrderPay),
	}
	err = o.Create()
	if err != nil {
		return nil, fmt.Errorf("订单创建失败")
	}
	amount := strconv.FormatFloat(float64(in.OrderAmount), 'f', 1, 64)
	pkgs := pkg.AS()
	pay := pkgs.ALiPay(o.GoodsTitle, o.OrdersSn, amount)
	return &mooc.OrderAddResponse{OrderId: int64(o.ID), Url: pay}, nil
}
